//
//  VSaleViewController.m
//  STL_ Animation
//
//  Created by DJtd on 16/3/30.
//  Copyright © 2016年 STL. All rights reserved.
//

#import "VSaleViewController.h"
#import "AppDelegate.h"
#import "STL.h"
#import "STLScrollView.h"
#import "VSaleCurrentListView.h"
#import "VSaleDynamicModel.h"
#import "VSaleTableVIewCell.h"
#import "VSaleDateView.h"
#import "VSalePastListModel.h"
#import "VSaleAlertController.h"
#import "ChannelPageMV_ViewController.h"

@interface VSaleViewController ()<STLScrollViewDelegate, UITableViewDelegate, UITableViewDataSource, VSaleDateViewDelegate, VSaleAlertControllerDelegate>

@property (nonatomic, strong) NSArray *locationArr;
@property (nonatomic, strong) UISegmentedControl *segmented;
@property (nonatomic, assign) NSInteger locationIndex;
@property (nonatomic, strong) STLScrollView *topScrollView;
@property (nonatomic, strong) VSaleCurrentListView *currentListView;
@property (nonatomic, strong) STLTableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) BOOL refresh;
@property (nonatomic, assign) NSInteger typeSelected;
@property (nonatomic, strong) VSaleDateView *dateView;
@property (nonatomic, strong) NSString *dateCode;

@end

@implementation VSaleViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    //
    self.view.backgroundColor = [UIColor blackColor];
    self.navigationItem.title = @"V榜";
    
    self.locationIndex = 2;
    self.locationArr = @[@"JP", @"US", @"ML", @"KR", @"HT"];
    self.dataSource = [NSMutableArray arrayWithCapacity:0];
    self.refresh = YES;
    
    self.page = 0;
    
    self.dateCode = @"0";
    
    [self creatSegmented];
    [self creatTopScrollView];
    [self creatCurrentListView];
    [self creatDateView];
    self.dateView.hidden = YES;
    [self creatTableView];
    [self currentListRequestWithType:self.locationArr[self.locationIndex]];
    
}

#pragma mark - creatSegmented
- (void)creatSegmented {
    self.segmented = [[UISegmentedControl alloc] initWithItems:@[@"打榜动态", @"往期榜单"]];
    self.segmented.frame = CGRectMake(5, 0, ScreenWidth - 10, ScreenHeight * 0.045);
    self.segmented.selectedSegmentIndex = 0;
    self.typeSelected = self.segmented.selectedSegmentIndex;
    self.segmented.tintColor = [UIColor colorWithRed:8/255.0 green:146/255.0 blue:114/255.0 alpha:1];
    [self.segmented setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]} forState:UIControlStateSelected];
    [self.segmented addTarget:self action:@selector(segmentedAction:) forControlEvents:UIControlEventValueChanged];
    
    [self.view addSubview:self.segmented];
}

#pragma mark - segmentedAction
- (void)segmentedAction:(UISegmentedControl *)sender {
    self.typeSelected = sender.selectedSegmentIndex;
    if (sender.selectedSegmentIndex == 0) {
//        self.typeSelected = 0;
        self.currentListView.hidden = NO;
        self.dateView.hidden = YES;
        self.refresh = YES;
        [self currentListRequestWithType:self.locationArr[self.locationIndex]];
    } else {
        self.currentListView.hidden = YES;
        self.dateView.hidden = NO;
        [self pastListRquestWithType:self.locationArr[self.locationIndex] withDate:@"0"];
    }
}

#pragma mark - creatTopScrollView 
- (void)creatTopScrollView {
    self.topScrollView = [[STLScrollView alloc] initWithFrame:CGRectMake(0, self.segmented.bounds.size.height, ScreenWidth, self.segmented.bounds.size.height) withTextArr:@[@"日本篇", @"欧美篇", @"内地篇", @"韩国篇", @"港台篇"] withIndex:self.locationIndex];
    self.topScrollView.delegate = self;
    [self.view addSubview:self.topScrollView];
}

#pragma mark - topScrollViewDelegate
- (void)indexOfDetailId:(NSInteger)detailId {
    self.locationIndex = detailId;
    self.page = 0;
    self.refresh = YES;
    if (self.segmented.selectedSegmentIndex == 0) {
        [self currentListRequestWithType:self.locationArr[self.locationIndex]];
    } else {
        [self pastListRquestWithType:self.locationArr[self.locationIndex] withDate:self.dateCode];
    }
    
}

#pragma mark - creatCurrentListView
- (void)creatCurrentListView {
    self.currentListView = [[VSaleCurrentListView alloc] initWithFrame:CGRectMake(0, self.topScrollView.frame.origin.y + self.topScrollView.bounds.size.height, ScreenWidth, ScreenHeight * 0.04)];
    
    [self.view addSubview:self.currentListView];
}

#pragma mark - currentListRequest 
- (void)currentListRequestWithType:(NSString *)type {
    [SJAFNetTool GEtNetWithUrl:[NSString stringWithFormat:@"http://mapi.yinyuetai.com/vchart/trend.json?D-A=0&area=%@&date=true&offset=%ld&size=20", type, self.page] WithBody:nil headerFile:Dictionary response:SJJSON success:^(id result) {
        
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        
        if (result) {
            if (self.refresh == YES) {
                [self.dataSource removeAllObjects];
            }
            
            VSaleDynamicModel *dynamicModel = [[VSaleDynamicModel alloc] initWithDataSource:result];
            self.currentListView.dynamicModel = dynamicModel;
            
            for (NSDictionary *dic in result[@"videos"]) {
                VSaleVideosDetailModel *videosDetailModel = [[VSaleVideosDetailModel alloc] initWithDataSource:dic];
                [self.dataSource addObject:videosDetailModel];
            }
            
            [self.tableView reloadData];
            
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }
        
    } failure:^(NSError *error) {
        [MBProgressHUD showAlertView:@"" andMessage:@"网络错误"];
    }];
}

#pragma mark - creatDateView
- (void)creatDateView {
    self.dateView = [[VSaleDateView alloc] initWithFrame:CGRectMake(0, self.topScrollView.frame.origin.y + self.topScrollView.bounds.size.height, ScreenWidth, ScreenHeight * 0.04)];
    self.dateView.delegate = self;
    [self.view addSubview:self.dateView];
}
#pragma mark - dateView请求数据协议方法
- (void)requestWithDateCode:(NSString *)dateCode {
    self.typeSelected = self.segmented.selectedSegmentIndex;
    self.dateCode = dateCode;
    [self pastListRquestWithType:self.locationArr[self.locationIndex] withDate:self.dateCode];
}
#pragma mark - dateView创建弹出框协议方法
- (void)creatAlertController {
    
    VSaleAlertController *alertController = [VSaleAlertController alertControllerWithTitle:@"\n\n\n\n\n\n\n\n\n" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    alertController.delegate = self;
    [self presentViewController:alertController animated:YES completion:^{
        
    }];
}
#pragma mark - 弹出框点击确定协议方法
- (void)requestWithDate:(NSString *)Code {
    [self pastListRquestWithType:self.locationArr[self.locationIndex] withDate:Code];
}

#pragma mark - pastListRequest
- (void)pastListRquestWithType:(NSString *)type withDate:(NSString *)date {
    [SJAFNetTool GEtNetWithUrl:[NSString stringWithFormat:@"http://mapi.yinyuetai.com/vchart/show.json?D-A=0&area=%@&datecode=%@", type, date] WithBody:nil headerFile:Dictionary response:SJJSON success:^(id result) {
        if (result) {
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            
            [self.dataSource removeAllObjects];
            
            VSalePastListModel *pastListModel = [[VSalePastListModel alloc] initWithDataSource:result];
            self.dateView.pastListModel = [[VSalePastListModel alloc] initWithDataSource:result];
            for (VSaleVideosDetailModel *videosDetailModel in pastListModel.videos) {
                
                [self.dataSource addObject:videosDetailModel];
            }
            
            [self.tableView reloadData];
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }
    } failure:^(NSError *error) {
        
        [MBProgressHUD showAlertView:@"" andMessage:@"网络错误"];
        
    }];
}

#pragma mark - creatTableView
- (void)creatTableView {
    self.tableView = [[STLTableView alloc] initWithFrame:CGRectMake(0, self.currentListView.origin.y + self.currentListView.bounds.size.height, ScreenWidth, ScreenHeight - self.segmented.bounds.size.height - self.topScrollView.bounds.size.height - self.currentListView.bounds.size.height - 60) style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:[VSaleTableVIewCell class] forCellReuseIdentifier:@"VSaleTableVIewCellIdentifier"];
    
    self.tableView.mj_header = [MJRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshAction)];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadAction)];
    
    [self.view addSubview:self.tableView];
}

- (void)refreshAction {
    self.refresh = YES;
    self.page = 0;
    if (self.typeSelected == 0) {
        [self currentListRequestWithType:self.locationArr[self.locationIndex]];
    } else {
        [self pastListRquestWithType:self.locationArr[self.locationIndex] withDate:self.dateCode];
    }
    [self.tableView.mj_header endRefreshing];
}

- (void)loadAction {
    
    if (self.typeSelected == 0) {
        self.refresh = NO;
        self.page += 20;
        [self currentListRequestWithType:self.locationArr[self.locationIndex]];
        [self.tableView.mj_footer endRefreshing];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return ScreenHeight * 0.23;
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    VSaleTableVIewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"VSaleTableVIewCellIdentifier"];
    
    cell.rankingLabel.text = [NSString stringWithFormat:@"%ld", indexPath.row + 1];
    cell.type = self.typeSelected;
    cell.videosDetailModel = self.dataSource[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ChannelPageMV_ViewController *channelMV_VC = [[ChannelPageMV_ViewController alloc] init];
    
    VSaleVideosDetailModel *model = self.dataSource[indexPath.row];
    
    channelMV_VC.idName = [NSString stringWithFormat:@"%@", model.Id];
    channelMV_VC.imageViewUrl = model.albumImg;
    
    [self.navigationController pushViewController:channelMV_VC animated:YES];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
